#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use Test::More tests => 11;

BEGIN {
        use_ok( 'Data::Form');
}

can_ok('Data::Form', qw/fields title new add_fields /);

my $form = Data::Form->new();

isa_ok($form,'Data::Form');

$form->add_fields(
		before => {
			#name		=> 'before',
   			required   => 1,
   			options    => [ qw/Mr Mrs Ms Dr/ ]
			},

		name => {
				#name		=> 'name',
				required   => 1,
				validators => {'%s must contain only word chars' => sub {shift;/^(\w|\s)+$/ ? 1 : 0 } },
			},
	
);

my $form1 = Data::Form->new(
	fields => [
		{
			name		=> 'before',
   			required   => 1,
   			options    => [ qw/Mr Mrs Ms Dr/ ]
			},

		{
			name		=> 'name',
			required   => 1,
			validators => {'%s must contain only word chars' => sub {shift;/^(\w|\s)+$/ ? 1 : 0 } },
			},
		]

);

#is_deeply($form, $form1, "2 Forms match");

$form->fill_in( name => 'Billy Bob', before => 'Bastard');
is( $form->valid, 0, 'Invalid Input' );

$form1->fill_in( name => 'Billy', before => 'Mr' );
is( $form1->valid, 1, 'Valid Input' );

isa_ok( $form->field('before'), 'Data::Form::Field::Option' );


#==============================================================================
# Cross field validations
# tests: 2
my $pw_form = Data::Form->new(
	fields => [
		{
			name		=> 'password',
   			required   => 1,
   			validators => { '%s must contain only word chars' => sub {shift;/^(\w|\s)+$/ ? 1 : 0 } },
		},

		{
			name		=> 'confirmpassword',
			required   => 1,
			validators => {'%s must contain only word chars' => sub {shift;/^(\w|\s)+$/ ? 1 : 0 } },
			},
		],
	validators => [
		{
			fields		=> [qw/ password confirmpassword /],
			error		=> 'PASSWORDS_MUST_MATCH',
			gets_error => 'password',		
			test			=> sub { $_[0] eq $_[1] }
		},
		]
);

isa_ok($pw_form, 'Data::Form');

$pw_form->fill_in(	password => 'dumb',
							confirmpassword => 'dumber');

ok($pw_form->field('password')->errors eq 'PASSWORDS_MUST_MATCH', 'passwords must match'); 

#==============================================================================
# Extraction Profiles
# tests: 3

my $xform = Data::Form->new(
	fields => [
			{			name		=> 'skippy',	},
			{			name		=> 'dippy',	},
			{			name		=> 'true',		},
		],
	profiles => [
				first	=> { skippy	=> 'skippy',
								true		=> 'true',
								},
				second => { skippy => 'parent',
									dippy  => 'child',
								}
		],
);
isa_ok($xform, 'Data::Form');
my %in = ( skippy	=> 'pbj',
				 dippy	=> 'chocolate',
				 true		=> 'dat'  );

$xform->fill_in(%in);

#diag( Dumper $xform );

is_deeply({$xform->extract('first')},     {skippy	=> 'pbj', true		=> 'dat'}, 'extracts ok');
is_deeply({$xform->extract('second')}, {parent	=> 'pbj', child	=> 'chocolate'}, 'extracts ok - renamed');
